<template>
  <!-- TODO:删除modal，改为组件 -->
  <je-table
    ref="xTable"
    border
    class="query-strategy"
    :stripe="false"
    size="mini"
    auto-resize
    show-overflow
    keep-source
    draggable
    show-header-overflow
    :store="tableData"
    resizable
    :edit-config="{
      trigger: 'click',
      mode: 'cell',
      showUpdateStatus: true,
    }"
    :row-config="{ isCurrent: false, isHover: false }"
    :loading="tableDataSet.loading"
    header-align="center"
    :cell-style="rowStyle"
    @drop="sort"
  >
    <!-- <je-column type="drag" /> -->
    <je-column field="SY_ORDERINDEX" title="序号" width="50" align="center" :edit-render="{}">
      <template #edit="{ row }">
        {{ row.SY_ORDERINDEX }}
      </template>
    </je-column>
    <je-column title="操作" width="200" align="center">
      <template #header>
        <i style="font-size: 16px; cursor: pointer" class="fal fa-plus" @click="addData"></i>
      </template>
      <template #default="{ row }">
        <span
          style="color: #006ed7; padding: 0 8px; display: inline-block; cursor: pointer"
          @click="doSave(row)"
          >保存</span
        >
        <span
          style="color: #d8001b; padding: 0 8px; display: inline-block; cursor: pointer"
          @click="doDelete(row)"
          >删除</span
        >
        <span
          style="color: #0a7900; padding: 0 8px; display: inline-block; cursor: pointer"
          @click="doDefault('1', row)"
          >默认</span
        >
        <span
          style="color: #979797; padding: 0 8px; display: inline-block; cursor: pointer"
          @click="doDefault('0', row)"
          >取消</span
        >
      </template>
    </je-column>

    <je-column field="QUERYSTRATEGY_NAME" title="名称" :edit-render="inputRender" width="220">
      <template #edit="{ row }">
        <je-input v-model:value="row.QUERYSTRATEGY_NAME" />
      </template>
    </je-column>
    <!-- <je-column
          field="QUERYSTRATEGY_QTYZ"
          title="其他语种"
          width="300"
          :edit-render="inputRender"
        >
          <template #edit="{ row }">
            <je-input v-model:value="row.QUERYSTRATEGY_QTYZ" />
          </template>
        </je-column> -->
    <je-column field="QUERYSTRATEGY_SQL" title="SQL" width="300" :edit-render="inputRender">
      <template #edit="{ row }">
        <je-input v-model:value="row.QUERYSTRATEGY_SQL" placeholder="and..." />
      </template>
    </je-column>
    <je-column
      field="QUERYSTRATEGY_SQL_REMARKS"
      title="SQL备注"
      min-width="300"
      :edit-render="inputRender"
    >
      <template #edit="{ row }">
        <je-input v-model:value="row.QUERYSTRATEGY_SQL_REMARKS" />
      </template>
      <template #default="{ row }">
        {{ row.QUERYSTRATEGY_SQL_REMARKS }}
        <i class="strategyicon jeicon jeicon-eye" @click="sqlPacked(row)"></i>
      </template>
    </je-column>
    <je-column field="QUERYSTRATEGY_FN" title="方法" width="60" align="center">
      <template #default="{ row }">
        <i
          :style="`cursor: pointer;color:${
            row.QUERYSTRATEGY_FN != undefined && row.QUERYSTRATEGY_FN != ''
              ? '#FAC502'
              : 'rgb(141, 152, 171)'
          }`"
          class="fas fa-bolt"
          @click="handerJs(row)"
        ></i>
      </template>
    </je-column>
    <je-column
      field="QUERYSTRATEGY_FGGNSQL"
      title="覆盖功能SQL"
      width="140"
      align="center"
      type="switch"
    >
      <!-- <template #default="{ row }">
        <je-checkbox v-model:checked="row.QUERYSTRATEGY_FGGNSQL" />
      </template> -->
    </je-column>
  </je-table>
  <AddQueryStrategy
    v-if="tableDataSet.addShow"
    :record-data="recordData"
    @chageState="chageState"
  />
</template>

<script>
  import { defineComponent, ref, reactive, onMounted } from 'vue';
  import { Input, Modal, Grid, Data } from '@jecloud/ui';
  import {
    getQueryStrategy,
    DeleteQueryStrategy,
    updateQueryStrategy,
    ChangeTranslateSql,
    DataMoveUpdate,
  } from '@/api/index';
  import { inputRender, numberRender } from '@/helper/edit-render';
  import AddQueryStrategy from './modal/add.vue';

  import { listenerEditorModal } from '@/helper/index.js';
  import { useFuncStore } from '@/store/func-store';

  export default defineComponent({
    name: 'QueryStrategy',
    components: {
      JeInput: Input,
      JeTable: Grid,
      JeColumn: Grid.Column,
      // JeInputNumber: InputNumber,
      // JeCheckbox: Checkbox,
      AddQueryStrategy,
    },
    props: {
      recordData: {
        type: Object,
        default: () => {
          return {};
        },
      },
    },
    emits: ['btnClick'],
    setup(props, { emit }) {
      const xTable = ref(null);
      const tableData = Data.Store.useGridStore({
        data: [],
      });
      const tableDataSet = reactive({ tableData: [], loading: true, addShow: false });
      const menuActive = reactive({ show: false, recordData: props.recordData, selectRec: {} });

      //点击编辑js
      const handerJs = (row) => {
        menuActive.selectRec = row;
        menuActive.recordData['eventType'] = 'default';
        menuActive.recordData['eventInfo'] = row.QUERYSTRATEGY_FN;
        menuActive.show = 'listenerEditor';
        const funcStore = useFuncStore();
        listenerEditorModal({
          funcId: funcStore.funcBean.id,
          eventType: 'default',
          eventInfo: row.QUERYSTRATEGY_FN,
          callback: (obj) => {
            btnClick({ type: 'ok', eventInfo: obj.eventInfo });
          },
        });
      };

      const btnClick = (obj) => {
        if (obj.type == 'ok') {
          menuActive.selectRec.QUERYSTRATEGY_FN = obj.eventInfo;
          const strData = JSON.stringify([
            {
              JE_CORE_QUERYSTRATEGY_ID: menuActive.selectRec.JE_CORE_QUERYSTRATEGY_ID,
              QUERYSTRATEGY_FN: obj.eventInfo,
            },
          ]);
          DataMoveUpdate({
            tableCode: 'JE_CORE_QUERYSTRATEGY',
            strData,
          })
            .then((data) => {
              Modal.message(data.message, 'success');
            })
            .catch((e) => {
              Modal.alert(e.message, 'error');
            });
        } else {
          menuActive.show = false;
        }
      };
      onMounted(() => {
        getTableData();
      });
      //初始化列表数据
      const getTableData = () => {
        const j_query = {
          custom: [
            {
              code: 'QUERYSTRATEGY_FUNCINFO_ID',
              value: props.recordData.id,
              type: '=',
              cn: 'and',
            },
            {
              type: 'and',
              value: [
                { code: 'QUERYSTRATEGY_USERID', type: 'isNull' },
                { code: 'QUERYSTRATEGY_USERID', type: '=', value: '', cn: 'or' },
              ],
            },
          ],
          order: [{ code: 'SY_ORDERINDEX', type: 'asc' }],
        };
        getQueryStrategy({
          tableCode: 'JE_CORE_QUERYSTRATEGY',
          limit: -1,
          j_query: JSON.stringify(j_query),
        })
          .then((data) => {
            // data.rows.forEach((item, index) => {
            //   if (item.QUERYSTRATEGY_FGGNSQL == undefined || item.QUERYSTRATEGY_FGGNSQL == '0') {
            //     item.QUERYSTRATEGY_FGGNSQL = false;
            //   } else {
            //     item.QUERYSTRATEGY_FGGNSQL = true;
            //   }
            // });
            tableData.loadData(data.rows);
            tableDataSet.loading = false;
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };

      //关闭弹窗
      const cancelModal = (modal) => {
        emit('btnClick');
      };
      //添加数据
      const addData = () => {
        tableDataSet.addShow = true;
      };
      const chageState = () => {
        tableDataSet.addShow = false;
        getTableData();
      };

      //删除
      const doDelete = (row) => {
        DeleteQueryStrategy({
          tableCode: 'JE_CORE_QUERYSTRATEGY',
          ids: row.JE_CORE_QUERYSTRATEGY_ID,
        })
          .then((data) => {
            Modal.message(data.message, 'success');
            xTable.value.$plugin.remove(row);
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      //保存
      const doSave = (rows) => {
        delete rows.__action__;
        // row.QUERYSTRATEGY_FGGNSQL = row.QUERYSTRATEGY_FGGNSQL ? '1' : '0';
        updateQueryStrategy({
          strData: JSON.stringify([rows]),
          funcId: props.recordData.id,
          tableCode: 'JE_CORE_QUERYSTRATEGY',
        })
          .then((data) => {
            Modal.message(data.message, 'success');
            xTable.value.store.commitRecord(rows);
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      //设置是否默认
      const doDefault = (type, row) => {
        if (row.QUERYSTRATEGY_DEF == type) {
          // Modal.message('无数据操作!', 'info');
          return false;
        }
        const strData = [];
        tableData.data.forEach((item) => {
          item.QUERYSTRATEGY_DEF = '0';
          if (item.JE_CORE_QUERYSTRATEGY_ID == row.JE_CORE_QUERYSTRATEGY_ID) {
            item.QUERYSTRATEGY_DEF = type;
          }
          strData.push({
            QUERYSTRATEGY_DEF: item.QUERYSTRATEGY_DEF,
            JE_CORE_QUERYSTRATEGY_ID: item.JE_CORE_QUERYSTRATEGY_ID,
          });
        });
        // const strData = [
        //   { QUERYSTRATEGY_DEF: type, JE_CORE_QUERYSTRATEGY_ID: row.JE_CORE_QUERYSTRATEGY_ID },
        // ];
        updateQueryStrategy({
          strData: JSON.stringify(strData),
          funcId: props.recordData.id,
          tableCode: 'JE_CORE_QUERYSTRATEGY',
        })
          .then((data) => {
            Modal.notice(data.message, 'success');
            getTableData();
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      const rowStyle = ({ row }) => {
        if (row.QUERYSTRATEGY_DEF == '1') {
          return {
            backgroundColor: '#E8FBCB',
          };
        }
      };
      //拖拽
      const sort = () => {
        const strData = [];
        tableData.data.forEach((item, index) => {
          strData.push({
            JE_CORE_QUERYSTRATEGY_ID: item.JE_CORE_QUERYSTRATEGY_ID,
            SY_ORDERINDEX: index + 1,
          });
        });
        updateQueryStrategy({
          strData: JSON.stringify(strData),
          funcId: props.recordData.id,
          tableCode: 'JE_CORE_QUERYSTRATEGY',
        })
          .then((data) => {
            Modal.notice(data.message, 'success');
            getTableData();
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      //sql装换自然语言
      const sqlPacked = (row) => {
        ChangeTranslateSql({
          funcId: props.recordData.id,
          sql: row.QUERYSTRATEGY_SQL,
        })
          .then((data) => {
            console.log(data);
            row.QUERYSTRATEGY_SQL_REMARKS = data;
          })
          .catch((e) => {
            Modal.alert(e.message, 'error');
          });
      };
      return {
        visibleModule: true,
        cancelModal,
        tableDataSet,
        addData,
        inputRender,
        numberRender,
        doDelete,
        doSave,
        doDefault,
        xTable,
        chageState,
        rowStyle,
        tableData,
        sort,
        sqlPacked,
        menuActive,
        btnClick,
        handerJs,
      };
    },
  });
</script>

<style lang="less" scoped>
  .query-strategy {
    :deep(.vxe-body--row) {
      .vxe-body--column .vxe-cell .strategyicon {
        line-height: revert !important;
        position: absolute;
        right: 5px;
        top: 5px;
        display: block;
      }
    }
  }
</style>
